<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
    okText="保存"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="物料编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                placeholder="物料编码"
                v-decorator="['materialCode', { rules: [{ required: true, message: '请输入物料编码!' }] }]"
                disabled
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="物料名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                placeholder="物料名称"
                v-decorator="['materialName', { rules: [{ required: true, message: '请输入物料名称!' }] }]"
                disabled
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="规格" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="规格" v-decorator="['specification']" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="颜色" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="颜色" v-decorator="['color']" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="批次号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="批次号" v-decorator="['batchNo']" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="库存状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                placeholder="请选择库存状态"
                v-decorator="['stockStatus', { rules: [{ required: true, message: '请选择库存状态!' }] }]"
                dictCode="wms_stock_status"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-item label="物料图片" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }">
              <j-image-upload
                v-decorator="['materialImages']"
                :number="5"
                :isMultiple="true"
                :bizPath="'wms/material'"
                :returnUrl="true"
                @change="handleMaterialImagesChange"
                @error="handleImageError"
              ></j-image-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { httpAction } from '@/api/manage'
import { inventoryEdit } from '@/api/wms'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JImageUpload from '@/components/jeecg/JImageUpload'

export default {
  name: 'InventoryEditModal',
  components: {
    JDictSelectTag,
    JImageUpload,
  },
  data() {
    return {
      title: '编辑库存信息',
      visible: false,
      model: {},
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      confirmLoading: false,
      form: this.$form.createForm(this),
      url: {
        edit: '/wms/inventory/edit',
      },
      materialImages: [], // 物料图片列表
    }
  },
  methods: {
    // 物料图片上传变更
    handleMaterialImagesChange(fileList) {
      console.log('物料图片变更:', fileList)

      // 当returnUrl为true时，fileList是字符串路径
      if (typeof fileList === 'string') {
        // 直接保存字符串路径
        this.materialImages = fileList
        console.log('保存物料图片路径:', this.materialImages)
      } else if (Array.isArray(fileList)) {
        // 如果是数组，转换为字符串路径
        const paths = fileList
          .map((file) => {
            if (file && typeof file === 'object' && file.response && file.response.message) {
              return file.response.message
            } else if (file && typeof file === 'string') {
              return file
            }
            return ''
          })
          .filter(Boolean)
          .join(',')

        this.materialImages = paths
        console.log('转换后的物料图片路径:', this.materialImages)
      } else {
        // 其他情况，设为空字符串
        console.warn('物料图片格式不正确:', fileList)
        this.materialImages = ''
      }

      // 更新表单值
      this.form.setFieldsValue({
        materialImages: this.materialImages,
      })
    },

    // 加载物料图片
    loadMaterialImages(images) {
      if (!images) {
        console.log('没有物料图片数据')
        return
      }

      try {
        console.log('加载物料图片:', images)

        // 如果images是对象，避免[object Object]错误
        if (typeof images === 'object') {
          console.warn('图片路径不应该是对象:', JSON.stringify(images))
          return
        }

        // 处理多个图片路径
        const imageArray = typeof images === 'string' ? images.split(',') : []
        const fileList = []

        // 为每个图片创建文件对象
        for (let i = 0; i < imageArray.length; i++) {
          if (imageArray[i]) {
            const filePath = imageArray[i].trim()
            // 获取文件名
            const fileName = filePath.substring(filePath.lastIndexOf('/') + 1)

            // 创建文件对象
            try {
              // 使用后端提供的正确URL格式：/sys/common/static/
              const fileUrl = window._CONFIG['domianURL'] + '/sys/common/static/' + filePath

              fileList.push({
                uid: `-${i + 1}`,
                name: fileName,
                status: 'done',
                url: fileUrl,
                response: {
                  status: 'history',
                  message: filePath,
                },
              })
              console.log(`处理图片 ${i + 1}/${imageArray.length}: ${filePath} -> ${fileUrl}`)
            } catch (e) {
              console.error(`处理图片路径出错 [${filePath}]:`, e)
            }
          }
        }

        // 设置文件列表
        this.materialImages = images // 直接使用原始字符串
        console.log('设置物料图片路径:', this.materialImages)

        // 设置表单字段值
        this.$nextTick(() => {
          this.form.setFieldsValue({
            materialImages: images,
          })
        })
      } catch (error) {
        console.error('加载物料图片失败:', error, '原始数据:', images)
      }
    },

    // 处理图片加载错误
    handleImageError(e) {
      console.error('图片加载失败:', e)
      e.target.style.display = 'none'
      const container = e.target.parentNode
      if (container) {
        const icon = document.createElement('i')
        icon.className = 'anticon anticon-picture'
        icon.style.fontSize = '24px'
        icon.style.color = '#d9d9d9'
        container.insertBefore(icon, e.target)

        const errorText = document.createElement('div')
        errorText.innerText = '图片不存在'
        errorText.style.color = '#ff4d4f'
        errorText.style.fontSize = '12px'
        errorText.style.marginTop = '4px'
        container.appendChild(errorText)
      }
    },

    show(record) {
      this.visible = true
      this.model = Object.assign({}, record)

      this.$nextTick(() => {
        this.form.resetFields()

        // 表单赋值
        this.form.setFieldsValue({
          id: this.model.id,
          materialCode: this.model.materialCode,
          materialName: this.model.materialName,
          specification: this.model.specification,
          color: this.model.color,
          batchNo: this.model.batchNo,
          stockStatus: this.model.stockStatus,
        })

        // 加载物料图片
        if (this.model.materialImages) {
          this.loadMaterialImages(this.model.materialImages)
        }
      })
    },

    handleOk() {
      const that = this

      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true

          // 组装提交数据
          let formData = Object.assign(this.model, values)

          // 处理物料图片
          try {
            // 从表单获取值
            const formImages = values.materialImages

            // 确保materialImages是字符串
            if (typeof formImages === 'string') {
              formData.materialImages = formImages
            } else if (formImages && typeof formImages === 'object') {
              if (Array.isArray(formImages)) {
                // 如果是数组，提取每个元素的路径
                formData.materialImages = formImages
                  .map((item) => {
                    if (typeof item === 'string') return item
                    if (item && item.response && item.response.message) return item.response.message
                    return ''
                  })
                  .filter(Boolean)
                  .join(',')
              } else if (formImages.response && formImages.response.message) {
                // 单个对象
                formData.materialImages = formImages.response.message
              } else {
                // 无法处理的对象，转为空字符串
                console.warn('无法处理的物料图片格式:', formImages)
                formData.materialImages = ''
              }
            } else {
              // 使用组件中保存的值
              formData.materialImages = this.materialImages || ''
            }

            console.log('提交的物料图片数据:', formData.materialImages)
          } catch (error) {
            console.error('处理物料图片出错:', error)
            formData.materialImages = ''
          }

          // 发送请求
          inventoryEdit(formData)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                that.visible = false
              } else {
                that.$message.warning(res.message)
              }
            })
            .catch((error) => {
              console.error('库存编辑请求失败:', error)
              that.$message.error('保存失败，请稍后重试')
            })
            .finally(() => {
              that.confirmLoading = false
            })
        } else {
          console.log('表单验证失败:', err)
          // 确保验证失败时不会一直显示loading状态
          that.confirmLoading = false
        }
      })
    },

    handleCancel() {
      this.visible = false
    },
  },
}
</script> 